package com.doraemon.module.buyer.controller;

import com.doraemon.common.exception.SellException;
import com.doraemon.enums.ResultEnum;
import com.doraemon.module.buyer.dto.OrderDTO;
import com.doraemon.module.buyer.form.OrderForm;
import com.doraemon.module.buyer.service.OrderService;
import com.doraemon.module.buyer.vo.ReturnVO;
import com.doraemon.utils.OrderFrom2OrderDTOConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author doraemon
 * @date 2017/12/7.
 */
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {
    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public ReturnVO create(@Valid OrderForm orderForm,
                           BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【订单创建】：orderForm={}",orderForm);
            throw  new SellException(ResultEnum.PARAM_ERROR.getCode()
                    ,bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO = OrderFrom2OrderDTOConverter.convert(orderForm);
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【订单创建】:orderDTO={}",orderDTO);
            throw  new SellException(ResultEnum.ORDERDE_DETATL_EMPTY);
        }
        OrderDTO dto=orderService.create(orderDTO);
        Map<String,String> orderIdMap = new HashMap<>();
        orderIdMap.put("orderId",dto.getOrderId());
        return ReturnVO.success(orderIdMap);
    }
    @GetMapping("/list")
    public ReturnVO list(@RequestParam("openid") String openid,
                         @RequestParam(value = "page",defaultValue = "0") Integer page,
                         @RequestParam(value = "size",defaultValue = "10") Integer size){
        if (StringUtils.isEmpty(openid)) {
            log.error("【订单列表】openid为空");
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        PageRequest pageRequest = new PageRequest(page,size);
        Page<OrderDTO> orderDTOS = orderService.findList(openid,pageRequest);
        return ReturnVO.success(orderDTOS.getContent());
    }
}
